import 'package:flutter/material.dart';
import 'package:flutter_swiper_plus/flutter_swiper_plus.dart';
import 'package:get/get.dart';
import 'package:yqmssa_app/config/app_config.dart';
import 'package:yqmssa_app/router/page_router.dart';
import 'package:yqmssa_app/views/index/request/index_request.dart';
import 'package:yqmssa_app/widget/marquee_widget.dart';

import 'home_manager.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final process = [
    AppConfig.imagePath("process1.png"),
    AppConfig.imagePath("double_right.png"),
    AppConfig.imagePath("process2.png"),
    AppConfig.imagePath("double_right.png"),
    AppConfig.imagePath("process3.png"),
    AppConfig.imagePath("double_right.png"),
    AppConfig.imagePath("process4.png"),
  ];

  final processNames = ["债务评估", "", "委托受理", "", "定制方案", "", "结案交付"];

  final data = Get.parameters;

  bool isBaseFunction = false;

  final serviceData = [
    {"icon": AppConfig.imagePath("service1.png"), "name": "信用卡逾期"},
    {"icon": AppConfig.imagePath("service2.png"), "name": "网贷逾期"},
    {"icon": AppConfig.imagePath("service3.png"), "name": "其他逾期"},
  ];

  @override
  void initState() {
    super.initState();
    if (data.isNotEmpty) {
      setState(() {
        isBaseFunction = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final manager = Get.put(HomeManager());
    return Scaffold(
      backgroundColor: const Color(0XFFF8FAFD),
      body: Stack(
        children: [
          Obx(() {
            return ListView(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              children: [
                const SizedBox(height: 40),
                const SizedBox(height: 32, width: double.maxFinite, child: MarqueeWidget()),
                const SizedBox(height: 16),
                if (manager.bannerData.isNotEmpty)
                  SizedBox(
                    width: double.maxFinite,
                    height: 180,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(12),
                      child: Swiper(
                        autoplay: true,
                        itemBuilder: (context, index) {
                          final url = manager.bannerData[index].image;
                          return Image.network(url, width: double.maxFinite, fit: BoxFit.fill);
                        },
                        itemCount: manager.bannerData.length,
                        pagination: const SwiperPagination(),
                        onTap: (index) {
                          if (isBaseFunction) return;
                          Get.toNamed(PageRouter.landing, parameters: {"id": "${manager.bannerData[index].video?.id ?? 0}"});
                        },
                      ),
                    ),
                  ),
                // ClipRRect(
                //   borderRadius: BorderRadius.circular(12),
                //   child: AspectRatio(
                //     aspectRatio: 16 / 9,
                //     child: MyCustomVideoPlayerWidget(
                //       autoPlay: true,
                //       videoUrl: manager.videosData[Random().nextInt(manager.videosData.length)].videofile,
                //       controlCall: (value) {
                //         manager.betterPlayerController.value = value;
                //       },
                //     ),
                //   ),
                // ),
                const SizedBox(height: 16),
                if (!isBaseFunction && AppConfig.appInitData.bannerImageSet!.bannerImageOpen == 1) ...[
                  GestureDetector(
                    onTap: () {
                      manager.showSheet(pushType: AppConfig.appInitData.bannerImageSet!.bannerImageType);
                    },
                    child: Image.network(
                      AppConfig.appInitData.bannerImageSet!.bannerImage,
                      errorBuilder: (context, obj, st) {
                        return Image.asset(AppConfig.imagePath("banner.png"));
                      },
                    ),
                  ),
                  const SizedBox(height: 15),
                ],
                const Text(
                  "服务项目",
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Color(0XFF333333)),
                ),
                const SizedBox(height: 12),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: List.generate(serviceData.length, (index) {
                    final data = serviceData[index];
                    return _serviceItem(icon: data["icon"] ?? "", name: data["name"] ?? "");
                  }),
                ),
                const SizedBox(height: 16),
                const Text(
                  "法律服务",
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Color(0XFF333333)),
                ),
                const SizedBox(height: 12),
                ...List.generate(manager.videosData.length, (index) {
                  final data = manager.videosData[index];
                  return _item(data: data, isBaseFunction: isBaseFunction);
                }),
                const SizedBox(height: 24),
              ],
            );
          }),
          if (!isBaseFunction && AppConfig.appInitData.indexSubmit == 1)
            Positioned(
              right: 0,
              top: Get.height * 0.6,
              child: InkWell(
                onTap: () {
                  manager.showSheet(pushType: AppConfig.appInitData.indexSubmitType);
                },
                child: Image.network(
                  AppConfig.appInitData.submitPicture,
                  scale: 2,
                  errorBuilder: (errContext, obj, st) {
                    return const SizedBox();
                  },
                ),
              ),
            ),
          if (isBaseFunction)
            Positioned(
              bottom: 80,
              left: 24,
              right: 24,
              height: 48,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(backgroundColor: const Color(0XFF5B77FF)),
                onPressed: () {
                  Get.back();
                },
                child: const Text(
                  "退出基本功能模式",
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white),
                ),
              ),
            ),
        ],
      ),
    );
  }
}

Widget _item({required VideoListDM data, bool isBaseFunction = false}) {
  return Container(
    margin: const EdgeInsets.only(bottom: 12),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(10),
      boxShadow: const [BoxShadow(color: Color(0XFFE6E6E6), blurRadius: 18)],
    ),
    child: InkWell(
      onTap: () {
        if (isBaseFunction) return;
        Get.toNamed(PageRouter.landing, parameters: {"id": "${data.id}"});
      },
      child: Container(
        width: double.maxFinite,
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(8), color: Colors.white),
        child: Column(
          children: [
            Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
              SizedBox(
                width: 116,
                height: 116,
                child: ClipRRect(borderRadius: BorderRadius.circular(8), child: Image.network(data.fengImage)),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(
                      height: 50,
                      child: Text(
                        data.title,
                        overflow: TextOverflow.ellipsis,
                        maxLines: 2,
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                          color: Color(0XFF333333),
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(data.subtitle, style: const TextStyle(color: Color(0XFF999999), fontSize: 12)),
                    const SizedBox(height: 6),
                    Row(
                      children: [
                        Text(
                          "${data.bmNum > 10000 ? "${(data.bmNum / 10000).toStringAsFixed(2)}万" : data.bmNum}人领取",
                          style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: Color(0XFFFF6760)),
                        ),
                        const SizedBox(width: 6),
                        Expanded(
                          child: Container(
                            padding: const EdgeInsets.symmetric(vertical: 6),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(4),
                              gradient: const LinearGradient(colors: [Color(0XFFFDDEBA), Color(0XFFE4B591)]),
                            ),
                            child: Text(
                              (AppConfig.appInitData.channelText?.listText ?? "").isEmpty ? "免费领取方案" : (AppConfig.appInitData.channelText?.listText ?? ""),
                              textAlign: TextAlign.center,
                              style: const TextStyle(fontWeight: FontWeight.w500, color: Color(0XFF4A1C02)),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ]),
            const SizedBox(height: 8),
            const Divider(height: 1, color: Color(0XFFE5E5E5)),
            const SizedBox(height: 6),
            Row(
              children: [
                Image.asset(AppConfig.imagePath("item_tag.png"), width: 16),
                const SizedBox(width: 8),
                Text(
                  data.tagsStr,
                  style: const TextStyle(color: Color(0XFF4A1C02), fontWeight: FontWeight.w500, fontStyle: FontStyle.italic),
                ),
              ],
            ),
          ],
        ),
      ),
    ),
  );
}

Widget _serviceItem({String icon = "", String name = ""}) {
  return Container(
    height: 110,
    width: 106,
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(8),
      color: const Color(0XFFFEF6F2),
    ),
    child: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(icon, width: 60, height: 60),
          const SizedBox(height: 6),
          Text(
            name,
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: Color(0XFF4A1C02),
            ),
          )
        ],
      ),
    ),
  );
}
